#define _CRT_SECURE_NO_WARNINGS 1
class Solution {

public:
    int idx = 0, h[2010], ne[5010], e[5010];
    int d[2010];

    void add(int a, int b) {
        e[idx] = b, ne[idx] = h[a], h[a] = idx++;
    }

    int topu(int n) {
        int num = 0;
        queue<int> q;
        for (int i = 0; i < n; i++) {
            if (d[i] == 0) {
                num++;
                q.push(i);
            }
        }
        while (!q.empty()) {
            int t = q.front();
            q.pop();

            for (int i = h[t]; i != -1; i = ne[i]) {
                int j = e[i];
                d[j]--;
                if (d[j] == 0)q.push(j), num++;
            }

        }
        return num;
    }
    bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
        memset(h, -1, sizeof h);
        for (int i = 0; i < numCourses; i++)d[i] = 0;
        for (int i = 0; i < 5010; i++)ne[i] = 0, e[i] = 0;
        for (auto it : prerequisites) {
            int a = it[0];
            int b = it[1];
            add(b, a);
            d[a]++;
        }

        int ans = topu(numCourses);
        if (ans == numCourses)return true;
        return false;


    }
};